<template>
  <div>
    <!-- 顶部面包屑标识与导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right" style="font-weight: 16">
      <el-breadcrumb-item :to="{ path: '/' }">
        <i class="el-icon-s-promotion"></i>后台管理
      </el-breadcrumb-item>
      <el-breadcrumb-item :to="{path:'/sys-admin/product/spuManagement'}">SPU台账</el-breadcrumb-item>
      <el-breadcrumb-item><span>{{ spu.name }}</span></el-breadcrumb-item>
    </el-breadcrumb>
    <el-divider></el-divider>
    <!-- “新增SPU”按钮 “返回列表”按钮-->
    <div style="margin-bottom: 20px">
      <el-button size="medium" type="primary" @click="openAddNewDialog">新增SKU</el-button>
      <el-button size="medium" type="warning" @click="$router.push('/sys-admin/product/spuManagement')">返回列表
      </el-button>
    </div>

    <!-- 新增SKU的对话框 -->
    <el-dialog title="新增SKU" :visible.sync="addSkuDialogVisible" width="50%">
      <el-form :model="addSkuRuleForm" :rules="skuRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <!-- SKU的固定属性 -->
        <el-form-item label="标题" prop="title">
          <el-input v-model="addSkuRuleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="条形码" prop="barCode">
          <el-input v-model="addSkuRuleForm.barCode"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input v-model="addSkuRuleForm.price">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <!-- 根据属性模板中的属性，动态生成的控件 -->
        <el-form-item :label="attribute.name" v-for="attribute in attributeList" :key="attribute.id">
          <!-- 输入框类型 -->
          <template v-if="attribute.inputType==INPUT_TYPE_TEXT">
            <el-input v-model="specificationObject[attribute.name]">
              <template v-if="attribute.unit" slot="append">{{ attribute.unit }}</template>
            </el-input>
          </template>
          <!-- 单选框类型 -->
          <template v-else-if="attribute.inputType==INPUT_TYPE_CHECKBOX_SINGLE">
            <el-radio-group v-model="specificationObject[attribute.name]">
              <el-radio :label="attribute.unit?value+attribute.unit:value"
                        v-for="value in attribute.valueList.split(',')">{{ value }}
                <span v-if="attribute.unit">{{ attribute.unit }}</span>
              </el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <!-- SKU的固定属性 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input v-model="addSkuRuleForm.stock"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存阈警值" prop="stockThreshold">
              <el-input v-model="addSkuRuleForm.stockThreshold"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="addSkuRuleForm.sort"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('ruleForm')">立即创建</el-button>
          <el-button @click="resetForm('ruleForm')">重置</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- SKU表格数据 -->
    <el-table :data="tableData" style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="demo-table-expand">
            <el-form-item label="标题" style="width: 100%"><span>{{ props.row.title }}</span></el-form-item>
            <br/>
            <el-form-item label="数据id"><span>{{ props.row.id }}</span></el-form-item>
            <el-form-item label="SPU id"><span>{{ props.row.spuId }}</span></el-form-item>
            <el-form-item label="条型码"><span>{{ props.row.barCode }}</span></el-form-item>
            <el-form-item label="属性模版id"><span>{{ props.row.attributeTemplateId }}</span></el-form-item>
            <el-form-item label="相册id"><span>{{ props.row.albumId }}</span></el-form-item>
            <el-form-item label="当前库存"><span>{{ props.row.stock }}</span></el-form-item>
            <el-form-item label="单价"><span>{{ props.row.price }}</span></el-form-item>
            <el-form-item label="库存预警阈值"><span>{{ props.row.stockThreshold }}</span></el-form-item>
            <el-form-item label="销量"><span>{{ props.row.sales }}</span></el-form-item>
            <el-form-item label="买家评论数量总和"><span>{{ props.row.commentCount }}</span></el-form-item>
            <el-form-item label="买家好评数量总和"><span>{{ props.row.positiveCommentCount }}</span></el-form-item>
            <el-form-item label="排序序号"><span>{{ props.row.sort }}</span></el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column prop="id" label="ID" width="80" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="title" label="标题" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="barCode" label="条型码" width="200" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="price" label="单价" width="100" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="stock" label="当前库存" width="100" align="center"
                       :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="stock" label="参数清单" width="100" align="center">
        <template slot-scope="scope">
          <el-button size="small" @click="openParamListDialog(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="100" align="center">
        <template slot-scope="scope">
          <el-button type="primary" size="mini" icon="el-icon-edit" circle
                     @click="openEditDialog(scope.row)"></el-button>
          <el-button type="danger" size="mini" icon="el-icon-delete" circle
                     @click="openDeleteConfirm(scope.row)"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 参数清单的对话框 -->
    <el-dialog class="sku-param-list" :title="this.skuInfo.title+'配置清单'" :visible.sync="checkDialogVisible"
               width="40%">
      <el-descriptions :column="1" border label-class-name="description-label">
        <el-descriptions-item v-for="param in skuInfo.params" :label="param.name">
          {{ param.value }}
        </el-descriptions-item>
      </el-descriptions>
    </el-dialog>

    <!-- 编辑的对话框 -->
    <el-dialog title="编辑SKU" :visible.sync="editSkuDialogVisible" width="50%">
      <el-form :model="editSkuRuleForm" :rules="skuRules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
        <!-- SKU的固定属性 -->
        <el-form-item label="标题" prop="title">
          <el-input v-model="editSkuRuleForm.title"></el-input>
        </el-form-item>
        <el-form-item label="条形码" prop="barCode">
          <el-input v-model="editSkuRuleForm.barCode"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="price">
          <el-input v-model="editSkuRuleForm.price">
            <template slot="append">元</template>
          </el-input>
        </el-form-item>
        <!-- 根据属性模板中的属性，动态生成的控件 -->
        <el-form-item :label="attribute.name" v-for="attribute in attributeList" :key="attribute.id">
          <!-- 输入框类型 -->
          <template v-if="attribute.inputType==INPUT_TYPE_TEXT">
            <el-input v-model="editSpecificationObject[attribute.name]">
              <template v-if="attribute.unit" slot="append">{{ attribute.unit }}</template>
            </el-input>
          </template>
          <!-- 单选框类型 -->
          <template v-else-if="attribute.inputType==INPUT_TYPE_CHECKBOX_SINGLE">
            <el-radio-group v-model="editSpecificationObject[attribute.name]">
              <el-radio :label="attribute.unit?value+attribute.unit:value"
                        v-for="value in attribute.valueList.split(',')">{{ value }}
                <span v-if="attribute.unit">{{ attribute.unit }}</span>
              </el-radio>
            </el-radio-group>
          </template>
        </el-form-item>
        <!-- SKU的固定属性 -->
        <el-row>
          <el-col :span="12">
            <el-form-item label="库存" prop="stock">
              <el-input v-model="editSkuRuleForm.stock"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="库存阈警值" prop="stockThreshold">
              <el-input v-model="editSkuRuleForm.stockThreshold"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="排序序号" prop="sort">
          <el-input v-model="editSkuRuleForm.sort"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitEditForm('ruleForm')">修改</el-button>
          <el-button type="warning" @click="resetForm('ruleForm')">重置</el-button>
          <el-button @click="editSkuDialogVisible=false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分页组件 -->
    <el-pagination
        style="float: right"
        @current-change="handleCurrentChange"
        :current-page.sync="currentPage"
        :page-size="pageSize"
        layout="total, prev, pager, next, jumper"
        :total="total">
    </el-pagination>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 表格数据
      tableData: [],
      // 当前显示的SKU列表的SPU数据
      spu: {
        id: '',
        name: '',
        attributeTemplateId: ''
      },
      // 需要显示清单的SKU
      skuInfo: {
        id:'',
        title: '',
        params: []
      },
      // sku属性列表
      attributeList: [
        {
          id: 0,
          name: '',
          description: '',
          type: 0,
          inputType: 0,
          valueList: '',
          unit: '',
          sort: 0,
          isAllowCustomize: 0
        }
      ],
      // 新增SKU的表单
      specificationObject: {},
      addSkuRuleForm: {
        spuId: '',
        title: 'Redmi Note 11 5G 流光紫 高配版 骁龙888 16GB 512GB',
        barCode: '10061767427568',
        price: '2999',
        stock: '1000',
        stockThreshold: '100',
        sort: '',
        specifications: ''
      },
      // 新增SKU和编辑SKU的验证规则
      skuRules: {
        title: [
          {required: true, message: '请输入标题', trigger: 'blur'},
          {min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur'}
        ],
        barCode: [
          {required: true, message: '请输入条形码', trigger: 'blur'},
          {pattern: /^[1-9]\d*$/, message: '只允许输入数字', trigger: 'blur'}
        ],
        price: [
          {required: true, message: '请输入售价', trigger: 'blur'},
        ],
        stock: [
          {required: true, message: '请输入库存', trigger: 'blur'}
        ],
        stockThreshold: [
          {required: true, message: '请输入库存阈警值', trigger: 'blur'}
        ],
        sort: [
          {required: true, message: '请输入排序序号', trigger: 'blur'}
        ]
      },
      // 常量：空间类型
      INPUT_TYPE_TEXT: 0,
      INPUT_TYPE_CHECKBOX_SINGLE: 1,
      INPUT_TYPE_CHECKBOX_MULTI: 2,
      // 新增SKU的对话框
      addSkuDialogVisible: false,
      // 参数清单的查看对话框
      checkDialogVisible: false,
      // 编辑表单
      editSpecificationObject: {},
      editSkuRuleForm: {
        spuId: '',
        title: 'Redmi Note 11 5G 流光紫 高配版 骁龙888 16GB 512GB',
        barCode: '10061767427568',
        price: '2999',
        stock: '1000',
        stockThreshold: '100',
        sort: '',
        specifications: ''
      },
      // 编辑SKU的对话框
      editSkuDialogVisible: false,
      // 分页数据-----------------
      // 当前页
      currentPage: 1,
      // 最大页数
      maxPage: 1,
      // 每页记录数
      pageSize: 5,
      // 总数据量
      total: 2,
    }
  },
  methods: {
    // 新增SKU按钮
    openAddNewDialog() {
      this.addSkuRuleForm.spuId = this.spu.id;
      this.addSkuDialogVisible = true;
    },
    // 提交新增表单
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.addSkuRuleForm.specifications = JSON.stringify(this.specificationObject);
          this.addSkuRuleForm.spuId = this.spu.id;
          let formData = this.qs.stringify(this.addSkuRuleForm);
          let url = 'http://localhost:9180/sku/add-new';
          console.log('url = ' + url);

          let localJwt = localStorage.getItem('localJwt');
          this.axios.create({'headers': {'Authorization': localJwt}})
              .post(url, formData).then(((response) => {
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {
              this.$message({
                showClose: true,
                message: '添加SKU成功！',
                type: 'success'
              });
              this.addSkuDialogVisible = false;
              this.resetForm(formName);
              this.loadSkuList();
            } else if (jsonResult.state == 40400) {
              this.$message({
                showClose: true,
                message: jsonResult.message,
                type: 'error'
              });
            } else {
              this.$message({
                showClose: true,
                message: jsonResult.message,
                type: 'error'
              });
            }
          }))

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 提交编辑表单
    submitEditForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.editSkuRuleForm.specifications = JSON.stringify(this.editSpecificationObject);
          this.editSkuRuleForm.spuId = this.spu.id;
          let formData = this.qs.stringify(this.editSkuRuleForm);
          let url = 'http://localhost:9180/sku/'+this.skuInfo.id+'/update';
          console.log('url = ' + url);

          let localJwt = localStorage.getItem('localJwt');
          this.axios.create({'headers': {'Authorization': localJwt}})
              .post(url, formData).then(((response) => {
            let jsonResult = response.data;
            if (jsonResult.state == 20000) {
              this.$message({
                showClose: true,
                message: '修改SKU成功！',
                type: 'success'
              });
              this.editSkuDialogVisible = false;
              this.resetForm(formName);
              this.loadSkuList();
            } else if (jsonResult.state == 40400) {
              this.$message({
                showClose: true,
                message: jsonResult.message,
                type: 'error'
              });
            } else {
              this.$message({
                showClose: true,
                message: jsonResult.message,
                type: 'error'
              });
            }
          }))

        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    // 查看按钮
    openParamListDialog(sku) {
      this.skuInfo.title = sku.title;
      let params = JSON.parse(sku.specifications);
      this.skuInfo.params = Object.keys(params).map(key =>({
        name:key,
        value:params[key]
      }));
      this.checkDialogVisible = true;
    },
    // 编辑按钮
    openEditDialog(sku) {
      this.skuInfo.id = sku.id;
      let url = 'http://localhost:9180/sku/' +sku.id;
      console.log('加载SKU详情的url = ' + url);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response)=>{
            let jsonResult = response.data;
            if (jsonResult.state==20000){
              this.editSkuRuleForm=jsonResult.data;
            }else {
              this.$alert(jsonResult.message, '查看SKU详情失败', {
                confirmButtonText: '确定',
                callback: action => {
                  this.loadSkuList();
                }
              });
            }
      })
      // 显示编辑对话框
      this.editSkuDialogVisible = true;
    },
    // 删除按钮
    openDeleteConfirm(sku) {
      this.$confirm('此操作将永久删除【' + sku.id + '-' + sku.title + '】SKU, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.handleDelete(sku);
      }).catch(() => {
      });
    },
    // 执行删除
    handleDelete(sku) {
      let url = 'http://localhost:9180/sku/' + sku.id + '/delete';
      console.log('url=' + url);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .post(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.$message({
            type: 'success',
            message: '删除SKU：' + sku.id + '-' + sku.title + '成功!'
          });
          this.loadSkuList();
        } else if (jsonResult.state == 40400) {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
              this.loadSkuList();
            }
          });
        } else {
          this.$alert(jsonResult.message, '错误', {
            confirmButtonText: '确定',
            callback: action => {
            }
          });
        }
      })
    },
    // 页码改变时
    handleCurrentChange(page) {
      this.$router.replace('?page=' + page);
      this.loadSkuList();
    },
    // 加载SPU信息
    loadSpuInfo() {
      // 从内存中取出spuId
      let spuId = localStorage.getItem('localSpuId');
      // 从地址栏获取spuId
      // let spuId = parseInt(this.$router.currentRoute.query.spuId);
      if (!spuId || spuId < 1) {
        let message = "参数错误，无法加载SPU数据！";
        this.$alert(message, '操作失败', {
          confirmButtonText: '确定',
          callback: action => {
            this.$router.push('/sys-admin/product/spuManagement');
            return;
          }
        });
      }
      let url = 'http://localhost:9180/spu/' + spuId;
      console.log('加载SPU信息时的url = ' + url);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.spu = jsonResult.data;
          this.loadSkuList();
          this.loadAttributeList();
        } else {
          this.$alert(jsonResult.message, '操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.$router.push('/sys-admin/product/spuManagement');
            }
          });
        }
      })
    },
    // 加载SKU列表
    loadSkuList() {
      // 从内存中取出spuId
      let spuId = localStorage.getItem('localSpuId');
      // 从地址栏获取spuId
      // let spuId = parseInt(this.$router.currentRoute.query.spuId);
      console.log('spuId=' + spuId);

      if (!spuId || spuId < 1) {
        let message = "参数错误，无法加载SKU数据！";
        this.$alert(message, '操作失败', {
          confirmButtonText: '确定',
          callback: action => {
            this.$router.push('/sys-admin/product/spuManagement');
            return;
          }
        });
      }

      let url = 'http://localhost:9180/spu/' + spuId + '/sku-list';
      console.log('url = ' + url);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.tableData = jsonResult.data.list;
          this.currentPage = jsonResult.data.currentPage;
          this.maxPage = jsonResult.data.maxPage;
          this.pageSize = jsonResult.data.pageSize;
          this.total = jsonResult.data.total;
        } else {
          this.$alert(jsonResult.message, '加载SKU列表操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.$router.push('/sys-admin/product/spuManagement');
            }
          });
        }
      })
    },
    // 根据属性模板ID加载属性列表
    loadAttributeList() {
      let url = 'http://localhost:9180/attributes/list/' + this.spu.attributeTemplateId;
      console.log('url = ' + url);

      let localJwt = localStorage.getItem('localJwt');
      this.axios.create({'headers': {'Authorization': localJwt}})
          .get(url).then((response) => {
        let jsonResult = response.data;
        if (jsonResult.state == 20000) {
          this.attributeList = jsonResult.data.list;
        } else {
          this.$alert(jsonResult.message, '加载属性列表操作失败', {
            confirmButtonText: '确定',
            callback: action => {
              this.$router.push('/sys-admin/product/spuManagement');
            }
          });
        }
      })
    },
  },
  mounted() {
    this.loadSpuInfo();
  }
}
</script>
<style>
.demo-table-expand {
  background-color: #e8e6e6;
  font-size: 20PX;
}

.demo-table-expand label {
  width: 150px;
  color: #99a9bf;
}

.demo-table-expand .el-form-item {
  margin-right: 0;
  margin-bottom: 0;
  width: 50%;
}

.sku-param-list {
}

.sku-param-list .description-label {
  width: 150px;
}
</style>
